﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;

namespace SilverlightDemo.ViewModels
{
    public class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
    {
        #region [INotifyPropertyChanged]

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region[INotifyDataErrorInfo]

        private readonly Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

        public void SetError(string propertyName, string errorMessage)
        {
            if (!errors.ContainsKey(propertyName))
                errors.Add(propertyName, new List<string> { errorMessage });

            RaiseErrorsChanged(propertyName);
        }

        protected void ClearError(string propertyName)
        {
            if (errors.ContainsKey(propertyName))
            {
                errors.Remove(propertyName);
                RaiseErrorsChanged(propertyName);
            }
        }

        protected void ClearAllErrors()
        {
            var _errors = errors.Select(error => error.Key).ToList();

            foreach (var propertyName in _errors)
                ClearError(propertyName);
        }

        public void RaiseErrorsChanged(string propertyName)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        public IEnumerable GetErrors(string propertyName)
        {
            if (propertyName == null) return null;
            return errors.ContainsKey(propertyName) ? errors[propertyName] : null;
        }

        public bool HasErrors
        {
            get { return errors.Count > 0; }
        }

        #endregion
    }
}
